//
//  HttpClient.m
//  YueMall
//
//  Created by a on 15/7/2.
//  Copyright (c) 2015年 yindan. All rights reserved.
//

#import "HttpClient.h"
#import "NSString+Additions.h"
#import "LoginViewController.h"
@implementation HttpClient
+(HttpClient*)shareClient{
    static HttpClient *_sharedClient=nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSURL *baseURL=[NSURL URLWithString:@""];
        NSURLSessionConfiguration *config=[NSURLSessionConfiguration defaultSessionConfiguration];
        [config setHTTPAdditionalHeaders:@{@"Accept":@"application/json;charset=utf-8"}];
        _sharedClient=[[HttpClient alloc]initWithBaseURL:baseURL sessionConfiguration:config];
        _sharedClient.responseSerializer=[AFJSONResponseSerializer serializer];
        _sharedClient.responseSerializer.acceptableStatusCodes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 10000)]; //允许200-299
        _sharedClient.responseSerializer.acceptableContentTypes = [NSSet setWithObjects: @"application/json", @"text/json", @"text/javascript", @"text/plain",@"charset=utf-8",@"text/html",nil];;
        _sharedClient.requestSerializer.timeoutInterval = 60;
        _sharedClient.requestSerializer.allowsCellularAccess = YES;
        [_sharedClient.requestSerializer setValue:@"application/json;text/plain;text/html" forHTTPHeaderField:@"Accept"];
        [_sharedClient.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        _sharedClient.requestSerializer.timeoutInterval = 20;
    });
    return _sharedClient;
}
-(NSArray*)otherExceptionTypeUrls{
    if (!_otherExceptionTypeUrls) {
        _otherExceptionTypeUrls = @[];
    }
    return _otherExceptionTypeUrls;
}
//HTTP形式进行请求
-(void)postWithUrl:(NSString*)url params:(NSDictionary*)dic suc:(void(^)(id results))sucBlock fail:(void(^)(NSString *error,NSInteger status))failBlock{
    [self postWithUrl:url params:dic showLoading:NO suc:sucBlock fail:failBlock];
}
//HTTP形式进行请求（二级方法）带是否显示loading的传参
-(void)postWithUrl:(NSString*)url params:(NSDictionary*)dic showLoading:(BOOL)showLoading suc:(void(^)(id results))sucBlock fail:(void(^)(NSString *error,NSInteger status))failBlock{
    self.requestSerializer = [AFJSONRequestSerializer serializer];
#ifdef __OPTIMIZE__
    //正式环境加密
    
#endif
    if ([LoginTools sharedTools].token) {
        [self.requestSerializer setValue:[LoginTools sharedTools].token forHTTPHeaderField:@"Authorization"];
        [self.requestSerializer setValue:[LoginTools sharedTools].appkey forHTTPHeaderField:@"appKey"];
        [self.requestSerializer setValue:[LoginTools sharedTools].userId forHTTPHeaderField:@"userId"];
    }
    // 显示loading
    if (showLoading) {
        [self progressShow];
    }
    NSLog(@"_________url______________%@",url);
    NSLog(@"_________params_____________%@",dic);
    [self POST:url parameters:dic progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        // 隐藏loading
        if (showLoading) {
            [self progressDismiss];
        }
        NSLog(@"________________%@",responseObject);
        switch ([[responseObject objectForKey:@"code"] intValue]) {
            case 200:
            {
                dispatch_async(dispatch_get_main_queue(), ^{
                    sucBlock([responseObject objectForKey:@"data"]);
                });
            }
                break;
            case 506:
            {
                LoginViewController *login = [[LoginViewController alloc]init];
                RTRootNavigationController *nav = [[RTRootNavigationController alloc]initWithRootViewControllerNoWrapping:login];
                [JumpTools setRootCtrl:nav];
            }
                break;
            case 507:
            {
                LoginViewController *login = [[LoginViewController alloc]init];
                RTRootNavigationController *nav = [[RTRootNavigationController alloc]initWithRootViewControllerNoWrapping:login];
                [JumpTools setRootCtrl:nav];
            }
                break;
            default:
            {
                if ([responseObject objectForKey:@"message"]) {
                    [self handleRequestException:responseObject fail:failBlock];
                }
            }
                break;
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        // 隐藏loading
        if (showLoading) {
            [self progressDismiss];
        }
        if (error.code == 3840) {
            LoginViewController *login = [[LoginViewController alloc]init];
            RTRootNavigationController *nav = [[RTRootNavigationController alloc]initWithRootViewControllerNoWrapping:login];
            [JumpTools setRootCtrl:nav];
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"_____________%@",error);
                failBlock(error.localizedDescription,error.code);
            });
        }
    }];
}

//get方式进行请求
-(void)get:(NSString*)url params:(NSDictionary*)dic suc:(void(^)(id results))sucBlock fail:(void(^)(NSString *error,NSInteger status))failBlock{
    NSLog(@"_________url______________%@",url);
    NSLog(@"_________params_____________%@",dic);
    if ([LoginTools sharedTools].token) {
        [self.requestSerializer setValue:[LoginTools sharedTools].token forHTTPHeaderField:@"Authorization"];
        [self.requestSerializer setValue:[LoginTools sharedTools].appkey forHTTPHeaderField:@"appKey"];
    }
    [self GET:url parameters:dic progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"________________%@",responseObject);
        switch ([[responseObject objectForKey:@"code"] intValue]) {
            case 200:
            {
                dispatch_async(dispatch_get_main_queue(), ^{
                    sucBlock([responseObject objectForKey:@"data"]);
                });
            }
                break;
            case 506:
            {
                LoginViewController *login = [[LoginViewController alloc]init];
                RTRootNavigationController *nav = [[RTRootNavigationController alloc]initWithRootViewControllerNoWrapping:login];
                [JumpTools setRootCtrl:nav];
            }
                break;
            case 507:
            {
                LoginViewController *login = [[LoginViewController alloc]init];
                RTRootNavigationController *nav = [[RTRootNavigationController alloc]initWithRootViewControllerNoWrapping:login];
                [JumpTools setRootCtrl:nav];
            }
                break;
            default:
            {
                if ([responseObject objectForKey:@"message"]) {
                    [self handleRequestException:responseObject fail:failBlock];
                }
            }
                break;
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        if (error.code == 3840) {
            LoginViewController *login = [[LoginViewController alloc]init];
            RTRootNavigationController *nav = [[RTRootNavigationController alloc]initWithRootViewControllerNoWrapping:login];
            [JumpTools setRootCtrl:nav];
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"_____________%@",error);
                failBlock(error.localizedDescription,error.code);
            });
        }
    }];
}

-(void)uploadImage:(UIImage*)image url:(NSString*)uploadUrl formDataParam:(NSDictionary*)formDataDic suc:(void(^)(id results))sucBlock fail:(void(^)(NSString *error,NSInteger status))failBlock{
    NSLog(@"_________url______________%@",uploadUrl);
    NSLog(@"_________params_____________%@",formDataDic);
    if ([LoginTools sharedTools].token) {
        [self.requestSerializer setValue:[LoginTools sharedTools].token forHTTPHeaderField:@"Authorization"];
        [self.requestSerializer setValue:[LoginTools sharedTools].appkey forHTTPHeaderField:@"appKey"];
        [self.requestSerializer setValue:[LoginTools sharedTools].userId forHTTPHeaderField:@"userId"];
    }
    [self POST:uploadUrl parameters:formDataDic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:UIImageJPEGRepresentation(image, 0.3) name:@"file" fileName:@"test.jpg" mimeType:@"image/jpeg"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        dispatch_async(dispatch_get_main_queue(), ^{
            sucBlock(responseObject);
        });
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"_____________%@",error);
            failBlock(error.localizedDescription,error.code);
        });
    }];
}
-(void)uploadFile:(NSData*)fileData fileName:(NSString*)fileName  url:(NSString*)uploadUrl formDataParam:(NSDictionary*)formDataDic suc:(void(^)(id results))sucBlock fail:(void(^)(NSString *error,NSInteger status))failBlock{
    NSLog(@"_________url______________%@",uploadUrl);
    NSLog(@"_________params_____________%@",formDataDic);
    NSArray *mimeTypeArr = [fileName componentsSeparatedByString:@"."];
    NSString *mimeTypeStr = [fileName lastPathComponent];
    if ([mimeTypeArr count]) {
        if ([[mimeTypeArr lastObject] isEqualToString:@"docx"]) {
            mimeTypeStr = @"application/vnd.openxmlformats-officedocument.wordprocessingml.document";
        }else if ([[mimeTypeArr lastObject] isEqualToString:@"doc"]){
            mimeTypeStr = @"application/msword";
        }else if ([[mimeTypeArr lastObject] isEqualToString:@"pdf"]){
            mimeTypeStr = @"application/pdf";
        }else{
            Toast(@"不支持的文件格式");
            return;
        }
    }
    if ([LoginTools sharedTools].token) {
        [self.requestSerializer setValue:[LoginTools sharedTools].token forHTTPHeaderField:@"Authorization"];
        [self.requestSerializer setValue:[LoginTools sharedTools].appkey forHTTPHeaderField:@"appKey"];
    }
    [self POST:uploadUrl parameters:formDataDic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:fileData name:@"file" fileName:fileName mimeType:mimeTypeStr];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        dispatch_async(dispatch_get_main_queue(), ^{
            sucBlock(responseObject);
        });
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"_____________%@",error);
            failBlock(error.localizedDescription,error.code);
        });
    }];
}
-(void)handleRequestException:(id)response fail:(void(^)(NSString *error,NSInteger status))failBlock{
    failBlock(EC_ISNullStr([response objectForKey:@"message"])?@"":[response objectForKey:@"message"],[[NSString stringWithFormat:@"%@",[response objectForKey:@"code"]]integerValue]);
}
-(void)handleRequestExceptionOther:(id)response fail:(void(^)(NSString *error,NSInteger status))failBlock{
    if (!EC_ISNullStr([[response objectForKey:@"errors"] objectForKey:@"phone"])) {
        failBlock([[response objectForKey:@"errors"] objectForKey:@"phone"],0);
    }else if (!EC_ISNullStr([[response objectForKey:@"errors"] objectForKey:@"password"])) {
        failBlock([[response objectForKey:@"errors"] objectForKey:@"password"],0);
    }else if (!EC_ISNullStr([[response objectForKey:@"errors"] objectForKey:@"verificationCode"])) {
        failBlock([[response objectForKey:@"errors"] objectForKey:@"verificationCode"],0);
    }
}
-(void)progressShow{
    
}

-(void)progressDismiss{

}

@end
